//
//  UserAccountViewModel.swift
//  Weibo
//
//  Created by 付启刚 on 15/12/16.
//  Copyright © 2015年 faq. All rights reserved.
//

import UIKit
import AFNetworking
//封装网络请和 业务逻辑
class UserAccountViewModel: NSObject {
    //定义用户模型对象的属性
    var userAccount:UserAccount?
    override init(){
        userAccount=UserAccount.loadAccount()
        super.init()
    }
    //计算性属性 用户是否登陆
    var userLogin:Bool{
        return userAccount?.access_token != nil
    }
    var userName:String?{
        return userAccount?.name
    }
    var headUrl:NSURL?{
        let url=NSURL(string: userAccount?.avatar_large ?? "")
        return url
    }
    var token:String?{
        return userAccount?.access_token
    }
    func loadAccessToken(code:String,finished:(isSuccess:Bool)->()){
        let urlString="oauth2/access_token"
        let parameters=["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        
        NetWorkTools .sharedTools.requestJSONDict(.POST,urlString:urlString, parameters: parameters) { (dict, error) -> () in
            if error != nil{
                //请求失败
                finished(isSuccess: false)
                //执行失败回调
                return
            }
            //字典转模型
            let userAccount=UserAccount(dict: dict!)
            self.loadUserInfo(userAccount,finished:finished)
            
        }
    }
    //获取用户信息
    private func loadUserInfo(userAccount:UserAccount,finished:(isSuccess:Bool)->()){
        let urlString="https://api.weibo.com/2/users/show.json"
        if let token=userAccount.access_token,userId=userAccount.uid{
            let parameters=["access_token":token,"uid":userId]
            NetWorkTools.sharedTools.requestJSONDict(.GET, urlString: urlString, parameters: parameters, finished: { (dict, error) -> () in
                if error != nil {
                    finished(isSuccess: false)
                    return
                }
                let avatar_large=dict!["avatar_large"]as!String
                let name=dict!["name"]as!String
                userAccount.avatar_large=avatar_large
                userAccount.name=name
                userAccount.saveAccount()
                finished(isSuccess: true)
            })
        }
    }
}